package rad.framework.mail;

import static org.jboss.seam.ScopeType.APPLICATION;

import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.context.FacesContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.mock.MockApplicationFactory;
import org.jboss.seam.mock.MockExternalContext;
import org.jboss.seam.mock.MockFacesContext;
import org.jboss.seam.mock.MockFacesContextFactory;
import org.jboss.seam.mock.MockLifecycle;
import org.jboss.seam.ui.facelet.ServletContextManager;

/**
 * Patch for https://jira.jboss.org/jira/browse/JBSEAM-3555
 * 
 * @author boudyacho
 */
@Name("org.jboss.seam.ui.facelet.facesContextFactory")
@Scope(APPLICATION)
@BypassInterceptors
@Install(dependencies = "org.jboss.seam.faces.renderer", precedence = Install.DEPLOYMENT)
@AutoCreate
public class RendererFacesContextFactory extends
		org.jboss.seam.ui.facelet.RendererFacesContextFactory {

	@Create
	public void create() {
		try {
			super.create();
		} catch (IllegalStateException e) {
			FactoryFinder.setFactory(FactoryFinder.APPLICATION_FACTORY,
					MockApplicationFactory.class.getName());
			FactoryFinder.setFactory(FactoryFinder.FACES_CONTEXT_FACTORY,
					MockFacesContextFactory.class.getName());
			new MockLifecycle();
			super.create();
		}
	}

	public FacesContext getFacesContext(ServletRequest request,
			ServletResponse response) {
		FacesContext ctx = super.getFacesContext(request, response);

		if (ctx == null) {
			ApplicationFactory applicationFactory = (ApplicationFactory) FactoryFinder
					.getFactory(FactoryFinder.APPLICATION_FACTORY);
			Application application = applicationFactory.getApplication();

			MockExternalContext externalContext = new MockExternalContext(
					ServletContextManager.instance());
			MockFacesContext facesContext = new MockFacesContext(
					externalContext, application);
			facesContext.setCurrent();

			ctx = super.getFacesContext(request, response);
		}

		return ctx;
	}

}
